<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.12.159';
$port = 98;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
$fp = fopen("php://stdout", "r");
fclose($fp);

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    print_r($msgsock);
    /* Send instructions. */
    //$msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    //socket_write($msgsock, $msg, strlen($msg));

        $buf ='';
        while ($buf = socket_read($msgsock, 2048, PHP_BINARY_READ)) {
            
            echo $buf;
            break;

        }
       $head_arr = explode("\n", $buf);
	$file_arr = explode(' ', $head_arr[0]);
        $file_name = substr($file_arr[1], 1);

	$_GET = array('a'=>'test');
var_dump($_SERVER);

	if(empty($file_name)) {
		$html = "<html><head><title>head</title></head><body><h1>test我的</h1></body></html>";
	} else {
		//if(isset($_GET)) {
		//	$args = $_GET
		//}
		//$cmd = "php5-cgi -f $file_name";
		include($file_name);
		//$html = `$cmd`;
	}
       
	
        
        $response =  "HTTP/1.1 200 OK\n".
		     "Server: stonew0.1\n".
		     "Content-Type: text/html;charset=UTF-8\n".
		     "Connection: close\n\n".$html;
	//$html = `php `
        
        socket_write($msgsock,  $response, strlen($response));
        //fwrite($msgsock,  $response, strlen($response));
        echo 'fasdf';

    socket_close($msgsock);
} while (true);

socket_close($sock);
?>


